class TodoApp {
  constructor() {
    this.todos = JSON.parse(localStorage.getItem('todos')) || [];
    this.filter = 'all';
    this.todoList = document.getElementById('todo-list');
    this.input = document.getElementById('todo-input');

    // 创建并隐藏一个文件上传控件（只创建一次）
    this.bgUpload = document.createElement('input');
    this.bgUpload.type = 'file';
    this.bgUpload.accept = 'image/*';
    this.bgUpload.style.display = 'none';
    document.body.appendChild(this.bgUpload);

    // 选择图片后处理
    this.bgUpload.addEventListener('change', this.changeBackground.bind(this));

    // 点击 body 空白处（不在 .todo-app 内）触发上传
    document.body.addEventListener('click', (e) => {
      const container = document.querySelector('.todo-app');
      
      // 如果找不到 container 或点击在 container 之外，就触发选择（并排除点击文件输入本身）
      if (container && !container.contains(e.target)) {
        this.bgUpload.click();
      }
    });

    // 加载已保存的背景（如果有）
    this.loadBackground();

    // 绑定其他 UI 事件
    this.bindEvents();

    // 初次渲染
    this.render();
    // 绑定清除背景按钮事件
    const deleteBtn = document.querySelector('.delete-bg-btn');
    if (deleteBtn) {
    deleteBtn.addEventListener('click', (e) => {
        e.stopPropagation(); // 避免触发背景上传
        document.body.style.backgroundImage = '';
        localStorage.removeItem('todo-bg');

        // 去掉半透明效果（两个都恢复）
        document.querySelectorAll('.todo-container, .todo-app, .todo-app1')
        .forEach(el => el.classList.remove('with-bg'));
    });
}

  }

  // 当用户选择图片后调用
  changeBackground(e) {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      const imageUrl = reader.result;
      document.body.style.backgroundImage = `url(${imageUrl})`;
      document.body.style.backgroundSize = 'cover';
      document.body.style.backgroundPosition = 'center';
      localStorage.setItem('todo-bg', imageUrl);

      // 使用你现有的 .todo-app 元素，添加类以变为半透明
      const containers = document.querySelectorAll('.todo-app, .todo-app1');
      containers.forEach(c => c.classList.add('with-bg'));

    };
    reader.readAsDataURL(file);
  }

  // 加载 localStorage 中的背景（如果存在）
  loadBackground() {
    const saved = localStorage.getItem('todo-bg');
    if (saved) {
      document.body.style.backgroundImage = `url(${saved})`;
      document.body.style.backgroundSize = 'cover';
      document.body.style.backgroundPosition = 'center';
      const containers = document.querySelectorAll('.todo-app, .todo-app1');
      containers.forEach(c => c.classList.add('with-bg'));


    }
  }

  bindEvents() {
    document.getElementById('add-btn').addEventListener('click', () => this.addTodo());
    this.input.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') this.addTodo();
    });
    document.querySelectorAll('.filters button').forEach(btn => {
      btn.addEventListener('click', (e) => this.changeFilter(e.target.dataset.filter));
    });
  }

  addTodo() {
    const text = this.input.value.trim();
    if (text === '') return;
    const newTodo = { id: Date.now(), text, completed: false };
    this.todos.push(newTodo);
    this.save();
    this.input.value = '';
    this.render();
  }

  toggleTodo(id) {
    this.todos = this.todos.map(todo =>
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    );
    this.save();
    this.render();
  }

  deleteTodo(id, li) {
    li.classList.add('fade-out');
    setTimeout(() => {
      this.todos = this.todos.filter(todo => todo.id !== id);
      this.save();
      this.render();
    }, 300);
  }

  changeFilter(filter) {
    this.filter = filter;
    document.querySelectorAll('.filters button').forEach(btn => btn.classList.remove('active'));
    const target = document.querySelector(`.filters button[data-filter="${filter}"]`);
    if (target) target.classList.add('active');
    this.render();
  }

  getFilteredTodos() {
    if (this.filter === 'active') return this.todos.filter(t => !t.completed);
    if (this.filter === 'completed') return this.todos.filter(t => t.completed);
    return this.todos;
  }

  save() {
    localStorage.setItem('todos', JSON.stringify(this.todos));
  }

  render() {
    this.todoList.innerHTML = '';
    this.getFilteredTodos().forEach(todo => {
      const li = document.createElement('li');
      if (todo.completed) li.classList.add('completed');

      const checkbox = document.createElement('span');
      checkbox.classList.add('custom-checkbox');
      if (todo.completed) checkbox.classList.add('checked');
      checkbox.addEventListener('click', (e) => {
        e.stopPropagation();
        this.toggleTodo(todo.id);
      });

      const text = document.createElement('span');
      text.textContent = todo.text;
      text.style.flex = '1';
      text.addEventListener('click', () => this.toggleTodo(todo.id));

      const delBtn = document.createElement('button');
      delBtn.classList.add('delete-btn');
      const img = document.createElement('img');
      img.src = 'images/垃圾桶.png';
      img.alt = '删除';
      img.classList.add('delete-icon');
      delBtn.appendChild(img);
      delBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        this.deleteTodo(todo.id, li);
      });

      li.appendChild(checkbox);
      li.appendChild(text);
      li.appendChild(delBtn);
      this.todoList.appendChild(li);
    });

    // 更新统计
    const total = this.todos.length;
    const active = this.todos.filter(t => !t.completed).length;
    const stats = document.getElementById('todo-stats');
    if (stats) stats.textContent = `未完成 ${active} 个，共 ${total} 个`;
  }
}

// 启动程序（替换旧的实例化）
new TodoApp();
